package com.cxl.controller;

import cn.hutool.jwt.JWT;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cxl.config.AjaxResult;
import com.cxl.enums.Sex;
import com.cxl.entity.User;
import com.cxl.feign.FeignServer;
import com.cxl.service.IUserService;
import com.cxl.springboot.starter.fileupload.FileResult;
import com.cxl.springboot.starter.fileupload.FileUpLoadService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 崔学磊
 * @since 2022-03-11
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private FileUpLoadService fileUpLoadService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private FeignServer feignServer;

    /*秘钥*/
    private String key = "123";


    /*登陆*/
    @PostMapping(value = "/login")
    public AjaxResult login(@RequestBody User user) {
        /*email不可为空*/
        if (!StringUtils.isNoneBlank(user.getEmail())) {
            return AjaxResult.err(500, "不可为空");
        }
        /*判断数据库是否有该用户信息*/
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", user.getEmail());
        User one = iUserService.getOne(queryWrapper);
        if (one == null) {
            return AjaxResult.err(500, "邮箱地址错误,请重新输入");
        }
        /*md5加密判断与数据库密码是否一致*/
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((key + user.getPwd()).getBytes(StandardCharsets.UTF_8));
        if (md5DigestAsHex.equals(one.getPwd())) {
            String token = JWT.create()
                    .setPayload("email", one.getEmail())
                    .setPayload("pwd", one.getPwd())
                    .setKey(key.getBytes(StandardCharsets.UTF_8))
                    .sign();
            return AjaxResult.ok(token);
        }
        return AjaxResult.err(500, "密码错误");
    }


    /*用户列表*/
    @Cacheable(value = "list")
    @PostMapping(value = "/list")
    public Page<User> list(@RequestBody User user) {
        return iUserService.findAll(user, user.getPageNum(), user.getPageSize());
    }

    /*feign远程调用+redis存取学历数据*/
    @GetMapping(value = "/getedu")
    public List getedu() {
        if (redisTemplate.hasKey("edu")) {
            return redisTemplate.opsForList().range("edu", 0, -1);
        }
        List list = feignServer.list();
        redisTemplate.opsForList().rightPushAll("edu", list);
        return list;
    }

    @Cacheable(value = "list")
    @GetMapping(value = "/calist")
    public List<User> calist() {
        return iUserService.list();
    }

    @GetMapping(value = "/getSex")
    public Sex[] sexes() {
        Sex[] values = Sex.values();
        return values;
    }


    @CacheEvict(value = "list")
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody User user) {
        //redis防重复提交
        if (!redisTemplate.opsForValue().setIfAbsent(JSON.toJSON(user), null, 20, TimeUnit.SECONDS)) {
            return AjaxResult.err(500, "不可重复提交");
        }
        redisTemplate.opsForValue().set(JSON.toJSONString(user), null);
        kafkaTemplate.send("test", "add", JSON.toJSONString(user));
        return AjaxResult.ok();
    }


    /*上传图片*/
    @PostMapping(value = "/tofile")
    public FileResult tofile(@RequestParam(value = "file") MultipartFile file) throws IOException {
        FileResult result = fileUpLoadService.upload(file);
        return result;
    }
}
